package com.yinxin.util;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.IOException;
import java.sql.Connection;

/**
 * @Author: YinXin
 * @Date: 2021/10/20 8:38
 * @Version: 1.0
 * @description:
 */
public class HttpUtil {
    private static CloseableHttpClient httpclient;
    private static RequestConfig requestConfig;
    static {
        // 创建httpclient对象
         httpclient = HttpClients.createDefault();
        //设置超时时间
         requestConfig = RequestConfig.custom()
                .setSocketTimeout(10000)
                .setConnectTimeout(10000)
                .build();
        //修改默认的cookie策略，消除警告。
        //RequestConfig defaultConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
    }
    public static CloseableHttpResponse getResponse(String url){
        //跑去网页链接
        //String url = "https://tieba.baidu.com/p/7575055375";
        // 创建get对象
        HttpGet get = new HttpGet(url);
        //get.setConfig(defaultConfig);
        get.setConfig(requestConfig);
        // 创建context对象
        HttpClientContext context = HttpClientContext.create();
        // 创建response对象
        CloseableHttpResponse response = null;
        try {
             response = httpclient.execute(get, context);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }

    public static void close(){
        try {
            httpclient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
